﻿using mozhi.smarterp.BasicData.Enums;
using System;
using System.Collections.Generic;
using System.Text;
using Volo.Abp;
using Volo.Abp.Domain.Entities.Auditing;
using Volo.Abp.MultiTenancy;

namespace mozhi.smarterp.BasicData.NumberRules
{
    public class DocumentNumberRule : AuditedAggregateRoot<Guid>, IMultiTenant
    {
        public Guid? TenantId { get; private set; }

        public DocumentType Type { get; private set; }

        public string Name { get; private set; }

        /// <summary>
        /// 是否默认规则
        /// </summary>
        public bool IsDefault {  get; private set; }

        /// <summary>
        /// 前缀
        /// </summary>
        public string Prefix {  get; private set; }

        /// <summary>
        /// 流水长度
        /// </summary>
        public int Flow‌Length {  get; private set; }

        private DocumentNumberRule() { }

        public DocumentNumberRule(Guid id, DocumentType type, string name, string prefix, int flowLength)
        {
            Id = id;
            Type = type;
            Name = name;
            Prefix = prefix;
            FlowLength = flowLength;


            Validate();
        }

        public void Change(string name, string prefix, int flowLength)
        {
            Name = name;
            Prefix = prefix;
            FlowLength = flowLength;

            Validate();
        }

        public void SetDefault(bool isDefault)
        {
            IsDefault = isDefault;
        }

        public string Next(string current)
        {
            current = current ?? "";

            string result;

            //不符合当前规则，直接返回第一个编号
            if (!current.StartsWith(Prefix))
            {
                result = $"{Prefix}{"000000000000000000000000000".Substring(0, FlowLength-1)}1";
                return result;
            }

            var flowNumber = current.Replace(Prefix, "");

            int flowNoValue;

            if (int.TryParse(flowNumber, out flowNoValue))
                flowNoValue = flowNoValue + 1;
            else
                flowNoValue = 1;

            result = $"{Prefix}{"000000000000000000000000000".Substring(0, FlowLength - 1 - flowNoValue.ToString().Length)}{flowNoValue}";

            return result;
        }

        #region
        private void Validate()
        {
            Check.NotDefaultOrNull<DocumentType>(Type, nameof(Type));
            Check.NotNullOrEmpty(Name, nameof(Name));
            Check.NotNullOrEmpty(Prefix, nameof(Prefix));

            if (FlowLength <= 0 || FlowLength > 20)
                throw new UserFriendlyException("流水长度必须大于0,小于20");
        }
        #endregion
    }
}
